package com.magicborrow.activity;

import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.magicborrow.Constants;
import com.magicborrow.R;
import com.magicborrow.adapter.CanBorrowingAdapter;
import com.magicborrow.adapter.WantBorrowingAdapter;
import com.magicborrow.beans.WantBorringListBean;
import com.magicborrow.beans.WaresListBean;
import com.magicborrow.enums.PriceModeEnum;
import com.magicborrow.utils.UserTools;
import com.magicborrow.utils.ViewPressedUtil;
import com.magicborrow.utils.VolleyTool;
import com.magicborrow.views.RefreshRecyclerView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;

import java.util.ArrayList;
import java.util.HashMap;

public class WantBorrowingInfoActivity extends BaseActivity implements View.OnClickListener, VolleyTool.HTTPListener {

    private ImageView imvHead;
    private TextView tvName;
    private TextView tvPublishTime;
    private TextView stuffName;
    private TextView tvTime;
    private TextView tvAddress;
    private TextView canBorrowingNumber;
    private RefreshRecyclerView rcWares;
    private WantBorringListBean.DataEntity.WantBorrowingBean bean;
    private ArrayList<WaresListBean.DataEntity.CanBorrowingBean> data;
    private CanBorrowingAdapter adapter;
    private int currentPage = 0;
    private boolean canEdit;
    private Button btnIGive;
    private TextView tvText;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_want_borrowing_info);

        findViewById(R.id.imb_more).setOnClickListener(this);
        findViewById(R.id.imb_more).setOnTouchListener(ViewPressedUtil.TouchPress);
        btnIGive = (Button) findViewById(R.id.btn_i_give);

        btnIGive.setOnTouchListener(ViewPressedUtil.TouchPress);
        imvHead = (ImageView) findViewById(R.id.imv_head);
        tvName = (TextView) findViewById(R.id.tv_name);
        tvPublishTime = (TextView) findViewById(R.id.tv_publish_time);
        stuffName = (TextView) findViewById(R.id.stuff_name);
        tvTime = (TextView) findViewById(R.id.tv_time);
        tvAddress = (TextView) findViewById(R.id.tv_address);
        canBorrowingNumber = (TextView) findViewById(R.id.can_borrowing_number);
        rcWares = (RefreshRecyclerView) findViewById(R.id.rc_wares);
        tvText = (TextView) findViewById(R.id.tv_text);
        putDataForView();
        data = new ArrayList<>();

        adapter = new CanBorrowingAdapter(data);
        rcWares.setAdapter(adapter);
        rcWares.setOnPullListener(new RefreshRecyclerView.onPullListener() {
            @Override
            public void onPullListener() {
                currentPage++;
                initData();

            }
        });
        rcWares.setOnRefreshListener(new RefreshRecyclerView.OnRefreshListener() {
            @Override
            public void onRefreshListener() {
                currentPage = 0;
                initData();
            }
        });
        initData();
    }

    private void initData() {
        HashMap<String, String> params = new HashMap<>();
        params.put("page", "" + currentPage);
        params.put("size", "20");
        params.put("id", "" + bean.getId());
        VolleyTool.get(Constants.URL_GET_CAN_BORROW, params, this, 0, WaresListBean.class);


    }

    private void putDataForView() {
        bean = (WantBorringListBean.DataEntity.WantBorrowingBean) getIntent().getSerializableExtra("stuff");
        canEdit = getIntent().getBooleanExtra("canEdit", false);
        DisplayImageOptions options = new DisplayImageOptions.Builder().displayer(new RoundedBitmapDisplayer(getResources().getDimensionPixelOffset(R.dimen._30dp))).build();

        ImageLoader.getInstance().displayImage(Constants.ADDRESS + bean.getUser().getAvatar80(),
                imvHead, options);
        tvName.setText(bean.getUser().getNickname());
        tvPublishTime.setText(bean.getCreated());
        tvAddress.setText(bean.getAddress());
        stuffName.setText(bean.getName());
        tvTime.setText("想借" + bean.getTimes() + PriceModeEnum.getModeStr(bean.getTimesMode()));
        canBorrowingNumber.setText(bean.getNumber() + "人可借");
        tvText.setText(""+bean.getDescription());

        if (!UserTools.isLogin(WantBorrowingInfoActivity.this) || bean.getUser().getId() != UserTools.getUser(this).getId()) {


            btnIGive.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //TODO implement
                    if (!UserTools.isLogin(WantBorrowingInfoActivity.this, true))
                        return;
                    Intent intent = new Intent(WantBorrowingInfoActivity.this, ICaLendActivity.class);
                    intent.putExtra("borrowId", bean.getId());
                    WantBorrowingInfoActivity.this.startActivity(intent);
                }
            });

        } else {
            if (canEdit) {
                btnIGive.setText("编辑求借");
                btnIGive.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(WantBorrowingInfoActivity.this, WantBorrowingActivity.class);
                        intent.putExtra("data", bean);
                        WantBorrowingInfoActivity.this.startActivity(intent);
                    }
                });
            } else {
                btnIGive.setVisibility(View.GONE);

            }

        }


    }

    @Override
    public void onClick(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.imb_more:
                showPopupWindow(view);
                //TODO implement
                break;
            case R.id.tv_help:
                //TODO implement
                //  showPopupWindow(view);
                break;
            case R.id.tv_complaints:
                //TODO implement
                if (!UserTools.isLogin(this, true))
                    return;
                intent = new Intent(this, ComplaintsActivity.class);
                intent.putExtra("id", "" + bean.getId());
                intent.putExtra("type", "" + 0);
                startActivity(intent);
                break;
         /*   case R.id.btn_i_give:

                break;*/
        }
    }

    private void showPopupWindow(View view) {

        // 一个自定义的布局，作为显示的内容
        View contentView = getLayoutInflater().inflate(
                R.layout.more_pop, null);
        TextView tvComplaints = (TextView) contentView.findViewById(R.id.tv_complaints);
        TextView tvHelp = (TextView) contentView.findViewById(R.id.tv_help);
        tvComplaints.setOnClickListener(this);
        tvHelp.setOnClickListener(this);


        final PopupWindow popupWindow = new PopupWindow(contentView,
                ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);

        popupWindow.setTouchable(true);

        popupWindow.setTouchInterceptor(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {

                Log.i("mengdd", "onTouch : ");

                return false;
                // 这里如果返回true的话，touch事件将被拦截
                // 拦截后 PopupWindow的onTouchEvent不被调用，这样点击外部区域无法dismiss
            }
        });

        // 如果不设置PopupWindow的背景，无论是点击外部区域还是Back键都无法dismiss弹框
        // 我觉得这里是API的一个bug
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        // 设置好参数之后再show
        popupWindow.showAsDropDown(view, 20, 20);

    }


    @Override
    public <T> void onResponse(T t, int requestCode) {
        rcWares.setLoadFinish();
        WaresListBean bean = (WaresListBean) t;
        if (bean.getCode() >= 0) {
            if (currentPage == 0)
                data.clear();
            data.addAll(bean.getData().getContent());
            rcWares.setIsLastPage(bean.getData().isLast());
            adapter.notifyDataSetChanged();

        } else {
            showShortMsg(bean.getMessage());
        }


    }

    @Override
    public void onErrorResponse(VolleyError error, int requestCode) {
        rcWares.setLoadFinish();

    }
}
